package com.liao.liaowenlong.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

public class MyService extends Service {
    private static final String TAG = "MyService";
    private boolean isStart = true;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind: ");
        return new MyBind();
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        spendTime();
        return super.onStartCommand(intent, flags, startId);
    }

    private int i = 0;

    private void spendTime() {
        new Thread() {
            @Override
            public void run() {
                while (isStart) {
                    try {
                        Log.d(TAG, "run: " + i++);
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "onUnbind: ");
        isStart = false;
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        isStart = false;
    }

    public class MyBind extends Binder {
        public int getCount() {
            return i;
        }

        public void setCount(int i) {
            MyService.this.i = i;
        }
    }
}
